using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Net.Http;
using System.Text;
using Newtonsoft.Json;
using System.Threading.Tasks;

namespace WindowsFormsDataBaice
{
    public class DoctorWorkstationForm : Form
    {
        private Panel headerPanel;
        private Panel leftPanel;
        private Panel rightPanel;
        private Panel bottomPanel;
        
        // 当前用户信息
        private int currentUserId;
        private string currentUserName;
        
        // 医生选择区域
        private Label lblDoctorTitle;
        private ComboBox cmbDoctors;
        private Button btnRefreshDoctors;
        
        // 待就诊列表区域
        private Label lblWaitingTitle;
        private DataGridView dgvWaitingPatients;
        private Button btnRefreshWaiting;
        
        // 当前选中的挂号信息
        private WaitingPatientInfo selectedRegistration;
        
        // 病历区域
        private Panel pnlMedicalRecord;
        private TextBox txtChiefComplaint;
        private TextBox txtDiagnosis;
        private TextBox txtTreatmentPlan;
        private TextBox txtRemark;
        private Button btnStartVisit;
        private Button btnFinishVisit;
        
        // 处方和检验单区域
        private TabControl tabMedical;
        private Button btnAddPrescription;
        private Button btnAddLabOrder;
        
        // 数据存储
        private List<DoctorInfo> doctors = new List<DoctorInfo>();
        private List<WaitingPatientInfo> waitingPatients = new List<WaitingPatientInfo>();
        private int? currentVisitId;
        private DoctorInfo selectedDoctor;

        public DoctorWorkstationForm(int userId, string userName)
        {
            this.currentUserId = userId;
            this.currentUserName = userName;
            InitializeComponent();
            SetupEventHandlers();
            LoadInitialData();
        }

        private void InitializeComponent()
        {
            // 设置窗体基本属性
            this.Size = new Size(1400, 900);
            this.Text = "医生工作站";
            this.StartPosition = FormStartPosition.CenterScreen;
            this.BackColor = UIStyleManager.BackgroundColor;
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;

            // 创建头部面板
            headerPanel = new Panel
            {
                Size = new Size(1400, 80),
                BackColor = UIStyleManager.PrimaryColor,
                Dock = DockStyle.Top
            };

            Label lblTitleIcon = new Label
            {
                Text = IconManager.Icons.User,
                Font = new Font("Segoe UI Emoji", 24),
                ForeColor = Color.White,
                Location = new Point(30, 20),
                AutoSize = true
            };

            Label titleLabel = new Label
            {
                Text = "医生工作站",
                Font = UIStyleManager.TitleFont,
                ForeColor = Color.White,
                Location = new Point(80, 25),
                AutoSize = true
            };

            headerPanel.Controls.Add(lblTitleIcon);
            headerPanel.Controls.Add(titleLabel);

            // 创建左侧面板（医生选择和待就诊列表）
            leftPanel = new Panel
            {
                Size = new Size(500, 740),
                Location = new Point(20, 90),
                BackColor = Color.White,
                BorderStyle = BorderStyle.FixedSingle,
                Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left
            };

            CreateDoctorSelectionArea();
            CreateWaitingPatientsArea();

            // 创建右侧面板（病历和处方检验单）
            rightPanel = new Panel
            {
                Size = new Size(850, 740),
                Location = new Point(530, 90),
                BackColor = Color.White,
                BorderStyle = BorderStyle.FixedSingle,
                Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right
            };

            CreateMedicalRecordArea();
            CreateMedicalTabsArea();

            // 创建底部按钮面板
            bottomPanel = new Panel
            {
                Size = new Size(1400, 70),
                BackColor = Color.FromArgb(240, 240, 240),
                Dock = DockStyle.Bottom
            };

            CreateBottomButtons();

            // 添加面板到窗体
            this.Controls.Add(headerPanel);
            this.Controls.Add(bottomPanel);
            this.Controls.Add(leftPanel);
            this.Controls.Add(rightPanel);
        }

        private void CreateDoctorSelectionArea()
        {
            // 医生选择标题
            lblDoctorTitle = new Label
            {
                Text = "选择医生",
                Font = new Font("微软雅黑", 14, FontStyle.Bold),
                Location = new Point(20, 20),
                Size = new Size(100, 30),
                ForeColor = UIStyleManager.PrimaryColor
            };

            // 医生下拉框
            cmbDoctors = new ComboBox
            {
                Location = new Point(20, 60),
                Size = new Size(350, 30),
                DropDownStyle = ComboBoxStyle.DropDownList,
                Font = UIStyleManager.BodyFont
            };

            // 刷新医生按钮
            btnRefreshDoctors = new Button
            {
                Text = "刷新",
                Location = new Point(380, 60),
                Size = new Size(80, 30),
                BackColor = Color.FromArgb(52, 152, 219),
                ForeColor = Color.White,
                FlatStyle = FlatStyle.Flat,
                Font = UIStyleManager.BodyFont
            };
            btnRefreshDoctors.FlatAppearance.BorderSize = 0;

            leftPanel.Controls.AddRange(new Control[] {
                lblDoctorTitle, cmbDoctors, btnRefreshDoctors
            });
        }

        private void CreateWaitingPatientsArea()
        {
            // 待就诊列表标题
            lblWaitingTitle = new Label
            {
                Text = "待就诊列表",
                Font = new Font("微软雅黑", 14, FontStyle.Bold),
                Location = new Point(20, 110),
                Size = new Size(150, 30),
                ForeColor = UIStyleManager.PrimaryColor
            };

            // 刷新待就诊按钮
            btnRefreshWaiting = new Button
            {
                Text = "刷新列表",
                Location = new Point(380, 110),
                Size = new Size(80, 30),
                BackColor = Color.FromArgb(46, 204, 113),
                ForeColor = Color.White,
                FlatStyle = FlatStyle.Flat,
                Font = UIStyleManager.BodyFont
            };
            btnRefreshWaiting.FlatAppearance.BorderSize = 0;

            // 待就诊列表
            dgvWaitingPatients = new DataGridView
            {
                Location = new Point(20, 150),
                Size = new Size(440, 560),
                AutoGenerateColumns = false,
                AllowUserToAddRows = false,
                ReadOnly = true,
                SelectionMode = DataGridViewSelectionMode.FullRowSelect,
                MultiSelect = false,
                Font = UIStyleManager.BodyFont,
                Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right
            };

            // 添加待就诊列表的列
            dgvWaitingPatients.Columns.Add("patientName", "患者姓名");
            dgvWaitingPatients.Columns.Add("cardNo", "就诊卡号");
            dgvWaitingPatients.Columns.Add("slotNo", "流水号");
            dgvWaitingPatients.Columns.Add("fee", "挂号费");
            dgvWaitingPatients.Columns.Add("createTime", "挂号时间");
            
            dgvWaitingPatients.Columns["patientName"].Width = 80;
            dgvWaitingPatients.Columns["cardNo"].Width = 100;
            dgvWaitingPatients.Columns["slotNo"].Width = 60;
            dgvWaitingPatients.Columns["fee"].Width = 60;
            dgvWaitingPatients.Columns["createTime"].Width = 120;

            leftPanel.Controls.AddRange(new Control[] {
                lblWaitingTitle, btnRefreshWaiting, dgvWaitingPatients
            });
        }

        private void CreateMedicalRecordArea()
        {
            // 病历信息面板
            pnlMedicalRecord = new Panel
            {
                Location = new Point(20, 20),
                Size = new Size(800, 300),
                BorderStyle = BorderStyle.FixedSingle,
                BackColor = Color.FromArgb(248, 249, 250)
            };

            Label lblMedicalTitle = new Label
            {
                Text = "病历信息",
                Font = new Font("微软雅黑", 14, FontStyle.Bold),
                Location = new Point(20, 15),
                Size = new Size(100, 25),
                ForeColor = UIStyleManager.PrimaryColor
            };

            // 主诉
            Label lblChiefComplaint = new Label
            {
                Text = "主诉:",
                Font = new Font("微软雅黑", 10),
                Location = new Point(20, 50),
                Size = new Size(60, 20)
            };

            txtChiefComplaint = new TextBox
            {
                Location = new Point(80, 45),
                Size = new Size(680, 25),
                Font = UIStyleManager.BodyFont
            };

            // 诊断
            Label lblDiagnosis = new Label
            {
                Text = "诊断:",
                Font = new Font("微软雅黑", 10),
                Location = new Point(20, 90),
                Size = new Size(60, 20)
            };

            txtDiagnosis = new TextBox
            {
                Location = new Point(80, 85),
                Size = new Size(680, 25),
                Font = UIStyleManager.BodyFont
            };

            // 治疗方案
            Label lblTreatmentPlan = new Label
            {
                Text = "治疗方案:",
                Font = new Font("微软雅黑", 10),
                Location = new Point(20, 130),
                Size = new Size(60, 20)
            };

            txtTreatmentPlan = new TextBox
            {
                Location = new Point(80, 125),
                Size = new Size(680, 60),
                Font = UIStyleManager.BodyFont,
                Multiline = true,
                ScrollBars = ScrollBars.Vertical
            };

            // 备注
            Label lblRemark = new Label
            {
                Text = "备注:",
                Font = new Font("微软雅黑", 10),
                Location = new Point(20, 205),
                Size = new Size(60, 20)
            };

            txtRemark = new TextBox
            {
                Location = new Point(80, 200),
                Size = new Size(680, 60),
                Font = UIStyleManager.BodyFont,
                Multiline = true,
                ScrollBars = ScrollBars.Vertical
            };

            // 开始接诊按钮
            btnStartVisit = IconManager.CreateSmallIconButton("【点我接诊】", IconManager.Icons.Save, 120, 35, ButtonStyle.Success);
            btnStartVisit.Location = new Point(640, 10);
            btnStartVisit.Enabled = true; // 【临时】设为启用以测试
            
            // 强制重新应用样式
            UIStyleManager.ApplyButtonStyle(btnStartVisit, ButtonStyle.Success);
            
            // 【移除手动鼠标悬停事件，让FlatAppearance处理】
            // 只保留光标变化
            btnStartVisit.MouseEnter += (s, e) => {
                if (btnStartVisit.Enabled) btnStartVisit.Cursor = Cursors.Hand;
            };
            btnStartVisit.MouseLeave += (s, e) => {
                btnStartVisit.Cursor = Cursors.Default;
            };

            // 结束就诊按钮
            btnFinishVisit = IconManager.CreateSmallIconButton("结束就诊", IconManager.Icons.Check, 100, 35, ButtonStyle.Primary);
            btnFinishVisit.Location = new Point(520, 10);
            btnFinishVisit.Enabled = false; // 初始禁用
            
            UIStyleManager.ApplyButtonStyle(btnFinishVisit, ButtonStyle.Primary);
            btnFinishVisit.MouseEnter += (s, e) => {
                if (btnFinishVisit.Enabled) btnFinishVisit.Cursor = Cursors.Hand;
            };
            btnFinishVisit.MouseLeave += (s, e) => {
                btnFinishVisit.Cursor = Cursors.Default;
            };

            // 简化的测试代码
            System.Diagnostics.Debug.WriteLine($"按钮创建: {btnStartVisit.Text}, Location: {btnStartVisit.Location}, Size: {btnStartVisit.Size}");

            // 【测试】创建一个简单的标准按钮
            Button testButton = new Button
            {
                Text = "测试按钮",
                Size = new Size(80, 35),
                Location = new Point(770, 10),
                BackColor = Color.Red,
                ForeColor = Color.White,
                Enabled = true
            };
            testButton.Click += (s, e) => MessageBox.Show("测试按钮被点击了！", "测试", MessageBoxButtons.OK, MessageBoxIcon.Information);
            testButton.MouseEnter += (s, e) => testButton.BackColor = Color.DarkRed;
            testButton.MouseLeave += (s, e) => testButton.BackColor = Color.Red;

            pnlMedicalRecord.Controls.AddRange(new Control[] {
                lblMedicalTitle, lblChiefComplaint, txtChiefComplaint,
                lblDiagnosis, txtDiagnosis, lblTreatmentPlan, txtTreatmentPlan,
                lblRemark, txtRemark, btnStartVisit, btnFinishVisit, testButton
            });

            rightPanel.Controls.Add(pnlMedicalRecord);
        }

        private void CreateMedicalTabsArea()
        {
            // Tab控件用于处方和检验单
            tabMedical = new TabControl
            {
                Location = new Point(20, 340),
                Size = new Size(800, 380),
                Font = UIStyleManager.BodyFont,
                Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right
            };

            // 处方标签页
            TabPage tabPrescription = new TabPage("处方管理");
            CreatePrescriptionTab(tabPrescription);

            // 检验单标签页
            TabPage tabLabOrder = new TabPage("检验单管理");
            CreateLabOrderTab(tabLabOrder);

            tabMedical.TabPages.Add(tabPrescription);
            tabMedical.TabPages.Add(tabLabOrder);

            rightPanel.Controls.Add(tabMedical);
        }

        private void CreatePrescriptionTab(TabPage tabPage)
        {
            // 添加处方按钮
            btnAddPrescription = IconManager.CreateSmallIconButton("开处方", IconManager.Icons.Plus, 100, 35, ButtonStyle.Primary);
            btnAddPrescription.Location = new Point(20, 20);
            btnAddPrescription.Enabled = true; // 【临时】设为启用以测试
            
            // 强制重新应用样式
            UIStyleManager.ApplyButtonStyle(btnAddPrescription, ButtonStyle.Primary);
            
            // 【移除手动鼠标悬停事件，让FlatAppearance处理】
            // 只保留光标变化
            btnAddPrescription.MouseEnter += (s, e) => {
                if (btnAddPrescription.Enabled) btnAddPrescription.Cursor = Cursors.Hand;
            };
            btnAddPrescription.MouseLeave += (s, e) => {
                btnAddPrescription.Cursor = Cursors.Default;
            };

            // 简化的测试代码
            System.Diagnostics.Debug.WriteLine($"处方按钮创建: {btnAddPrescription.Text}, Location: {btnAddPrescription.Location}, Size: {btnAddPrescription.Size}");

            // 处方列表
            DataGridView dgvPrescriptions = new DataGridView
            {
                Location = new Point(20, 70),
                Size = new Size(740, 270),
                AutoGenerateColumns = false,
                AllowUserToAddRows = false,
                ReadOnly = true,
                SelectionMode = DataGridViewSelectionMode.FullRowSelect,
                Font = UIStyleManager.BodyFont,
                Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right
            };

            // 添加处方列表的列
            dgvPrescriptions.Columns.Add("prescriptionNo", "处方号");
            dgvPrescriptions.Columns.Add("type", "类型");
            dgvPrescriptions.Columns.Add("amount", "金额");
            dgvPrescriptions.Columns.Add("createTime", "开立时间");
            dgvPrescriptions.Columns.Add("status", "状态");

            tabPage.Controls.AddRange(new Control[] { btnAddPrescription, dgvPrescriptions });
        }

        private void CreateLabOrderTab(TabPage tabPage)
        {
            // 添加检验单按钮
            btnAddLabOrder = IconManager.CreateSmallIconButton("开检验单", IconManager.Icons.Plus, 100, 35, ButtonStyle.Warning);
            btnAddLabOrder.Location = new Point(20, 20);
            btnAddLabOrder.Enabled = false;

            // 检验单列表
            DataGridView dgvLabOrders = new DataGridView
            {
                Location = new Point(20, 70),
                Size = new Size(740, 270),
                AutoGenerateColumns = false,
                AllowUserToAddRows = false,
                ReadOnly = true,
                SelectionMode = DataGridViewSelectionMode.FullRowSelect,
                Font = UIStyleManager.BodyFont,
                Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right
            };

            // 添加检验单列表的列
            dgvLabOrders.Columns.Add("orderNo", "检验单号");
            dgvLabOrders.Columns.Add("itemName", "检验项目");
            dgvLabOrders.Columns.Add("price", "费用");
            dgvLabOrders.Columns.Add("createTime", "开立时间");
            dgvLabOrders.Columns.Add("status", "状态");

            tabPage.Controls.AddRange(new Control[] { btnAddLabOrder, dgvLabOrders });
        }

        private void CreateBottomButtons()
        {
            // 刷新全部按钮
            Button btnRefreshAll = IconManager.CreateSmallIconButton("刷新全部", IconManager.Icons.Refresh, 100, 45, ButtonStyle.Primary);
            btnRefreshAll.Location = new Point(400, 15);
            btnRefreshAll.Click += BtnRefreshAll_Click;

            // 关闭按钮
            Button btnClose = IconManager.CreateSmallIconButton("关闭", IconManager.Icons.Close, 100, 45, ButtonStyle.Danger);
            btnClose.Location = new Point(520, 15);
            btnClose.Click += BtnClose_Click;

            bottomPanel.Controls.Add(btnRefreshAll);
            bottomPanel.Controls.Add(btnClose);
        }

        private void SetupEventHandlers()
        {
            btnRefreshDoctors.Click += BtnRefreshDoctors_Click;
            btnRefreshWaiting.Click += BtnRefreshWaiting_Click;
            cmbDoctors.SelectedIndexChanged += CmbDoctors_SelectedIndexChanged;
            dgvWaitingPatients.SelectionChanged += DgvWaitingPatients_SelectionChanged;
            btnStartVisit.Click += BtnStartVisit_Click;
            btnFinishVisit.Click += BtnFinishVisit_Click;
            btnAddPrescription.Click += BtnAddPrescription_Click;
            btnAddLabOrder.Click += BtnAddLabOrder_Click;
        }

        private async void LoadInitialData()
        {
            try
            {
                await LoadDoctors();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载数据失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private async Task LoadDoctors()
        {
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.Timeout = TimeSpan.FromSeconds(30);
                    client.DefaultRequestHeaders.Clear();
                    client.DefaultRequestHeaders.Add("Accept", "application/json");

                    string url = "http://101.201.170.32:5115/api/Doctor/Doctor/GetDoctors?pageIndex=1&pageSize=100";
                    var response = await client.GetAsync(url);
                    string responseContent = await response.Content.ReadAsStringAsync();

                    System.Diagnostics.Debug.WriteLine($"医生列表请求: {url}");
                    System.Diagnostics.Debug.WriteLine($"响应: {responseContent}");

                    if (response.IsSuccessStatusCode)
                    {
                        var doctorResponse = JsonConvert.DeserializeObject<DoctorResponse>(responseContent);
                        if (doctorResponse?.pageData != null)
                        {
                            doctors = doctorResponse.pageData;
                            cmbDoctors.Items.Clear();
                            cmbDoctors.Items.Add("请选择医生");
                            
                            foreach (var doctor in doctors)
                            {
                                cmbDoctors.Items.Add($"{doctor.doctorName} - {doctor.departmentName}");
                            }
                            cmbDoctors.SelectedIndex = 0;
                        }
                        else
                        {
                            MessageBox.Show("未找到医生数据", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                    else
                    {
                        MessageBox.Show($"访问医生列表失败: {response.StatusCode}\n{response.ReasonPhrase}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"网络请求失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private async Task LoadWaitingPatients()
        {
            if (selectedDoctor == null) return;

            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.Timeout = TimeSpan.FromSeconds(30);
                    client.DefaultRequestHeaders.Clear();
                    client.DefaultRequestHeaders.Add("Accept", "application/json");

                    string visitDate = DateTime.Now.ToString("yyyy-MM-dd");
                    string url = $"http://101.201.170.32:5166/api/DoctorWorkstation/waiting-patients?doctorId={selectedDoctor.id}&visitDate={visitDate}";
                    
                    var response = await client.GetAsync(url);
                    string responseContent = await response.Content.ReadAsStringAsync();

                    System.Diagnostics.Debug.WriteLine($"待就诊列表请求: {url}");
                    System.Diagnostics.Debug.WriteLine($"响应: {responseContent}");

                    if (response.IsSuccessStatusCode)
                    {
                        dynamic apiResponse = JsonConvert.DeserializeObject(responseContent);
                        if (apiResponse?.code == 200 && apiResponse?.data != null)
                        {
                            waitingPatients = JsonConvert.DeserializeObject<List<WaitingPatientInfo>>(apiResponse.data.ToString());
                            UpdateWaitingPatientsGrid();
                        }
                        else
                        {
                            waitingPatients.Clear();
                            UpdateWaitingPatientsGrid();
                            string message = apiResponse?.msg?.ToString() ?? "未找到待就诊患者";
                            MessageBox.Show(message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                    else
                    {
                        MessageBox.Show($"加载待就诊列表失败: {response.StatusCode}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"网络请求失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void UpdateWaitingPatientsGrid()
        {
            dgvWaitingPatients.Rows.Clear();
            foreach (var patient in waitingPatients)
            {
                var row = dgvWaitingPatients.Rows.Add();
                dgvWaitingPatients.Rows[row].Cells["patientName"].Value = patient.patientName;
                dgvWaitingPatients.Rows[row].Cells["cardNo"].Value = patient.cardNo;
                dgvWaitingPatients.Rows[row].Cells["slotNo"].Value = patient.slotNo;
                dgvWaitingPatients.Rows[row].Cells["fee"].Value = $"¥{patient.fee:F2}";
                dgvWaitingPatients.Rows[row].Cells["createTime"].Value = patient.createTime.ToString("MM-dd HH:mm");
                dgvWaitingPatients.Rows[row].Tag = patient;
            }
        }

        // 事件处理方法
        private async void BtnRefreshDoctors_Click(object sender, EventArgs e)
        {
            await LoadDoctors();
        }

        private async void BtnRefreshWaiting_Click(object sender, EventArgs e)
        {
            await LoadWaitingPatients();
        }

        private async void CmbDoctors_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbDoctors.SelectedIndex > 0)
            {
                selectedDoctor = doctors[cmbDoctors.SelectedIndex - 1];
                await LoadWaitingPatients();
            }
            else
            {
                selectedDoctor = null;
                waitingPatients.Clear();
                UpdateWaitingPatientsGrid();
            }
        }

        private void DgvWaitingPatients_SelectionChanged(object sender, EventArgs e)
        {
            if (dgvWaitingPatients.SelectedRows.Count > 0)
            {
                selectedRegistration = dgvWaitingPatients.SelectedRows[0].Tag as WaitingPatientInfo;
                
                // 【调试】强制启用按钮进行测试
                btnStartVisit.Enabled = true;
                btnAddPrescription.Enabled = true;
                
                // 调试输出
                System.Diagnostics.Debug.WriteLine($"选择患者: {selectedRegistration?.patientName}, 按钮状态: {btnStartVisit.Enabled}");
                
                // 清空病历信息
                txtChiefComplaint.Text = "";
                txtDiagnosis.Text = "";
                txtTreatmentPlan.Text = "";
                txtRemark.Text = "";
                currentVisitId = null;
                
                // 【注释掉】禁用处方和检验单按钮
                // btnAddPrescription.Enabled = false;
                // btnAddLabOrder.Enabled = false;
            }
            else
            {
                // 没有选择任何行时
                selectedRegistration = null;
                btnStartVisit.Enabled = false;
                System.Diagnostics.Debug.WriteLine("取消选择，按钮已禁用");
            }
        }

        private async void BtnStartVisit_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Debug.WriteLine("【点我接诊】按钮被点击了！");
            
            // 【修复】直接从选中行获取患者信息，而不依赖selectedRegistration变量
            if (dgvWaitingPatients.SelectedRows.Count == 0)
            {
                MessageBox.Show("请选择患者", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            
            // 直接从选中行获取患者信息
            selectedRegistration = dgvWaitingPatients.SelectedRows[0].Tag as WaitingPatientInfo;
            
            // 【调试】输出详细的选择状态
            System.Diagnostics.Debug.WriteLine($"选中行数: {dgvWaitingPatients.SelectedRows.Count}");
            var tag = dgvWaitingPatients.SelectedRows[0].Tag;
            System.Diagnostics.Debug.WriteLine($"Tag类型: {tag?.GetType()?.Name ?? "null"}");
            System.Diagnostics.Debug.WriteLine($"Tag值: {tag}");
            System.Diagnostics.Debug.WriteLine($"selectedRegistration是否为null: {selectedRegistration == null}");
            
            if (selectedRegistration == null)
            {
                MessageBox.Show("患者信息获取失败，请重新选择", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            // 暂时移除主诉必填验证，允许空主诉
            // if (string.IsNullOrEmpty(txtChiefComplaint.Text.Trim()))
            // {
            //     MessageBox.Show("请填写主诉", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //     return;
            // }



            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.Timeout = TimeSpan.FromSeconds(30);
                    client.DefaultRequestHeaders.Clear();
                    client.DefaultRequestHeaders.Add("Accept", "application/json");

                    var visitData = new
                    {
                        registrationId = selectedRegistration.registrationId,
                        chiefComplaint = txtChiefComplaint.Text.Trim(),
                        diagnosisText = txtDiagnosis.Text.Trim(),
                        treatmentPlan = txtTreatmentPlan.Text.Trim(),
                        remark = txtRemark.Text.Trim()
                    };

                    var json = JsonConvert.SerializeObject(visitData, Formatting.Indented);
                    var content = new StringContent(json, Encoding.UTF8, "application/json");

                    string url = "http://101.201.170.32:5166/api/DoctorWorkstation/start-visit";
                    var response = await client.PostAsync(url, content);
                    string responseContent = await response.Content.ReadAsStringAsync();

                    System.Diagnostics.Debug.WriteLine($"开始接诊请求: {json}");
                    System.Diagnostics.Debug.WriteLine($"响应: {responseContent}");

                    if (response.IsSuccessStatusCode)
                    {
                        dynamic apiResponse = JsonConvert.DeserializeObject(responseContent);
                        if (apiResponse?.code == 200 && apiResponse?.data != null)
                        {
                            currentVisitId = (int)apiResponse.data;
                            MessageBox.Show("开始接诊成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            
                            // 启用处方和检验单按钮
                            btnAddPrescription.Enabled = true;
                            btnAddLabOrder.Enabled = true;
                            
                            // 启用结束就诊按钮
                            btnFinishVisit.Enabled = true;
                            
                            // 【修复】保持当前患者信息，不要清空
                            // selectedRegistration = null; // 注释掉这行
                            
                            // 【修复】保持病历信息，医生可能需要继续填写
                            // txtChiefComplaint.Text = "";
                            // txtDiagnosis.Text = "";
                            // txtTreatmentPlan.Text = "";
                            // txtRemark.Text = "";
                            
                            // 【修复】保持接诊按钮启用状态，但改变文本提示当前状态
                            btnStartVisit.Text = "当前就诊中";
                            btnStartVisit.Enabled = false; // 防止重复接诊
                            
                            // 【修复】不要立即刷新列表，保持当前状态
                            // await LoadWaitingPatients();
                        }
                        else
                        {
                            string errorMessage = apiResponse?.msg?.ToString() ?? "开始接诊失败";
                            MessageBox.Show(errorMessage, "失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    else
                    {
                        MessageBox.Show($"开始接诊失败: {response.StatusCode}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"网络请求失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private async void BtnAddPrescription_Click(object sender, EventArgs e)
        {
            if (currentVisitId == null)
            {
                MessageBox.Show("请先开始接诊", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;


            }

            // 打开处方编辑对话框
            using (var form = new PrescriptionForm(currentVisitId.Value))
            {
                if (form.ShowDialog() == DialogResult.OK)
                {
                    // 处方添加成功，刷新处方列表
                    MessageBox.Show("处方添加成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    // 这里可以刷新处方列表显示
                }
            }
        }

        private async void BtnAddLabOrder_Click(object sender, EventArgs e)
        {
            if (currentVisitId == null)
            {
                MessageBox.Show("请先开始接诊", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            // 打开检验单编辑对话框
            using (var form = new LabOrderForm(currentVisitId.Value))
            {
                if (form.ShowDialog() == DialogResult.OK)
                {
                    // 检验单添加成功，刷新检验单列表
                    MessageBox.Show("检验单添加成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    // 这里可以刷新检验单列表显示
                }
            }
        }

        private async void BtnFinishVisit_Click(object sender, EventArgs e)
        {
            if (currentVisitId == null)
            {
                MessageBox.Show("当前没有正在进行的就诊", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            var result = MessageBox.Show($"确认结束当前就诊吗？\n患者：{selectedRegistration?.patientName}", "确认", 
                MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            
            if (result == DialogResult.Yes)
            {
                // 重置状态，准备接诊下一个患者
                currentVisitId = null;
                selectedRegistration = null;
                
                // 清空病历信息输入框
                txtChiefComplaint.Text = "";
                txtDiagnosis.Text = "";
                txtTreatmentPlan.Text = "";
                txtRemark.Text = "";
                
                // 重置按钮状态
                btnStartVisit.Text = "【点我接诊】";
                btnStartVisit.Enabled = false; // 需要选择患者后才能启用
                btnFinishVisit.Enabled = false;
                btnAddPrescription.Enabled = false;
                btnAddLabOrder.Enabled = false;
                
                // 清除选择
                dgvWaitingPatients.ClearSelection();
                
                // 刷新待就诊列表
                await LoadWaitingPatients();
                
                MessageBox.Show("就诊结束，可以选择下一个患者", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private async void BtnRefreshAll_Click(object sender, EventArgs e)
        {
            await LoadDoctors();
            if (selectedDoctor != null)
            {
                await LoadWaitingPatients();
            }
        }

        private void BtnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }

    // 数据模型类
    public class WaitingPatientInfo
    {
        public int registrationId { get; set; }
        public string cardNo { get; set; }
        public int patientId { get; set; }
        public string patientName { get; set; }
        public string slotNo { get; set; }
        public DateTime createTime { get; set; }
        public decimal fee { get; set; }
    }
} 